import axios from 'axios'
import store from '@/store'
import Nprogress from 'nprogress'
import { Message } from 'element-ui';
//进度条
Nprogress.configure({ showSpinner: false });

// create an axios instance
const instance = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 30000
});

//请求拦截器
instance.interceptors.request.use(
  (config) => {
    let token = store.state.user.token
    if (token) {
      config.headers.token = token
    }
    Nprogress.start()
    return config
  },
  error => {
    Message.error("请求拦截失败")
    return Promise.reject(error)
  }
)

////响应拦截器
instance.interceptors.response.use(
  (response) => {
     const res = response.data 
     if(res.code === 200 || res.code === 20000){
         return res
     }else if(res.code === 20001){
       localStorage.removeItem("key_token")
     }else{
      Message.error("获取数据失败")
      return Promise.reject(error);
     }
     
  },
  (error) =>{
     Message.error("发送请求失败")
     return Promise.reject(error);
  }
)

export default instance
